package com.dfa.nypl.location;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParserException;
import com.dfa.nypl.common.PopupPanel;
import com.dfa.nypl.common.WebService;
import com.dfa.nypl.entity.LibraryLocation;
import com.dfa.nypl.entity.ObjectUtils;
import com.dfa.nypl.main.R;
import com.dfa.nypl.tellafriend.TellAFriend;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.telephony.TelephonyManager;
import android.text.StaticLayout;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.LinearLayout.LayoutParams;

public class Statistics extends MapActivity {

	private ProgressBar progressBarLetter, progressBarRaise;
	private TextView totalLetter, totalRaise, goalLetter, goalRaise;
	private ImageButton viewLetterByBranch;

	private LinearLayout helpSoFarLayout, viewLetterLayout;

	private MapView mapview;
	private MapController mapController;
	private MyLocationOverlay me;

	public static boolean isHelpSoFarScreen = true;
	private List<LibraryLocation> mListOfLocation;
	private GeoPoint firstPoint;

	private TelephonyManager telephonyManager;
	private WakeLock lock;
	private ConnectivityManager connectivityManager;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.statistic_screen);

		connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

		telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

		initWakeLock();

		isHelpSoFarScreen = true;

		setProgressBarVisibility(true);

		progressBarLetter = (ProgressBar) findViewById(R.id.progressbar_letter);
		progressBarRaise = (ProgressBar) findViewById(R.id.progressbar_raise);

		totalLetter = (TextView) findViewById(R.id.total_letter);
		totalRaise = (TextView) findViewById(R.id.total_raise);
		goalLetter = (TextView) findViewById(R.id.goal_letter);
		goalRaise = (TextView) findViewById(R.id.goal_raise);
		if (isConnected()) {
			new InitDataTask().execute();
		} else {
			Toast.makeText(Statistics.this, "Network unable to connect",
					Toast.LENGTH_SHORT).show();
		}

		helpSoFarLayout = (LinearLayout) findViewById(R.id.help_so_far_layout);
		viewLetterLayout = (LinearLayout) findViewById(R.id.view_letter_by_branch_layout);

		viewLetterByBranch = (ImageButton) findViewById(R.id.view_letter_by_branch);
		viewLetterByBranch.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				setLetterByBranchView();
				if (isConnected()) {
					// draw marker
					new DrawPoiTask().execute();
				} else {
					Toast.makeText(Statistics.this,
							"Network unable to connect", Toast.LENGTH_SHORT)
							.show();
				}

			}
		});

		// MAP VIEW
		mapview = (MapView) findViewById(R.id.map_view);
		mapController = mapview.getController();
		mapController.setZoom(15);

		LinearLayout zoomLayout = (LinearLayout) findViewById(R.id.zoom_view);
		View zoomView = mapview.getZoomControls();
		zoomLayout.addView(zoomView, new LinearLayout.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
		mapview.displayZoomControls(true);

		// END MAP VIEW

	}

	@Override
	protected boolean isRouteDisplayed() {

		return false;
	}

	@Override
	protected void onPause() {
		super.onPause();
		lock.release();
	}

	@Override
	protected void onResume() {
		super.onResume();
		lock.acquire();

	}

	private void initWakeLock() {
		PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
		lock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK
				| PowerManager.ON_AFTER_RELEASE, "LiveGPSTraking");
	}

	private boolean isConnected() {
		if (telephonyManager == null || connectivityManager == null) {
			return false;
		}

		final boolean roaming = telephonyManager.isNetworkRoaming();
		final NetworkInfo info = connectivityManager.getActiveNetworkInfo();

		return info != null && info.isConnected() && !roaming;
	}

	private void setHelpSoFarView() {
		viewLetterLayout.setVisibility(View.GONE);
		helpSoFarLayout.setVisibility(View.VISIBLE);

		isHelpSoFarScreen = true;
	}

	private void setLetterByBranchView() {
		viewLetterLayout.setVisibility(View.VISIBLE);
		helpSoFarLayout.setVisibility(View.GONE);

		isHelpSoFarScreen = false;
	}

	// Custom item over on map popup
	private class CustomItem extends OverlayItem {
		private Drawable marker;
		private String city;
		private String countLetter;

		public CustomItem(GeoPoint point, String name, String address,
				String city, String countLetter, Drawable marker) {
			super(point, name, address);
			this.city = city;
			this.countLetter = countLetter;
			this.marker = marker;
		}

		public void setMarker(Drawable marker) {
			this.marker = marker;
		}

		public String getCity() {
			return city;
		}

		public String getCountLetter() {
			return countLetter;
		}

		@Override
		public Drawable getMarker(int totalOfLetters) {
			Drawable result = marker;
			setState(result, totalOfLetters);
			return (result);
		}
	}

	// Add marker on mapview
	private class PoiItemOverlay extends ItemizedOverlay<CustomItem> {

		private List<CustomItem> items = new ArrayList<CustomItem>();
		CustomItem item = null;

		public PoiItemOverlay() {
			super(null);
			Drawable blueMarker = getMarker(R.drawable.blue_dot);
			Drawable greenMarker = getMarker(R.drawable.green_dot);
			Drawable purpleMarker = getMarker(R.drawable.violet_dot);
			Drawable redMarker = getMarker(R.drawable.red_dot);

			if (mListOfLocation != null && mListOfLocation.size() > 0) {
				for (LibraryLocation entry : mListOfLocation) {
					if (entry != null) {
						GeoPoint p = new GeoPoint((int) (entry.getLat() * 1E6),
								(int) (entry.getLon() * 1E6));
						String name = entry.getName();
						String address = entry.getAddress();
						String city = entry.getCity() + "," + entry.getState();
						String countLetter = "Number of letters submitted: "
								+ entry.getCountLetter();

						if (entry.getCountLetter() <= 500) {
							item = new CustomItem(p, name, address, city,
									countLetter, redMarker);
						} else if (entry.getCountLetter() > 500
								&& entry.getCountLetter() <= 1000) {
							item = new CustomItem(p, name, address, city,
									countLetter, purpleMarker);

						} else if (entry.getCountLetter() > 1000
								&& entry.getCountLetter() <= 2000) {
							item = new CustomItem(p, name, address, city,
									countLetter, blueMarker);

						} else if (entry.getCountLetter() > 2000) {
							item = new CustomItem(p, name, address, city,
									countLetter, greenMarker);
						}

						items.add(item);
					}

				}
			}

			populate();
		}

		@Override
		public void draw(Canvas canvas, MapView mapView, boolean shadow) {
			// TODO Auto-generated method stub
			super.draw(canvas, mapView, shadow);
		}

		@Override
		protected com.dfa.nypl.location.Statistics.CustomItem createItem(int i) {
			return items.get(i);
		}

		@Override
		public int size() {
			return (items.size());
		}

		@Override
		protected boolean onTap(int i) {
			CustomItem item = getItem(i);
			GeoPoint pt = (GeoPoint) item.getPoint();
			addPopupOfLocation(item);
			mapController.animateTo(pt);
			return (true);
		}

		private Drawable getMarker(int resource) {
			Drawable marker = getResources().getDrawable(resource);

			marker.setBounds(0, 0, marker.getIntrinsicWidth(), marker
					.getIntrinsicHeight());

			boundCenter(marker);

			return (marker);
		}

		// add popup of location
		private void addPopupOfLocation(CustomItem item) {
			mapview.removeAllViews();
			final PopupPanel panel = new PopupPanel(R.layout.poi_map_popup,
					mapview, Statistics.this);
			View view = panel.getView();
			TextView mapPoiName = (TextView) view
					.findViewById(R.id.map_poi_name);
			TextView mapPoiAddress = (TextView) view
					.findViewById(R.id.map_poi_address);
			TextView mapPoiCity = (TextView) view
					.findViewById(R.id.map_poi_city);
			TextView totalOfLeter = (TextView) view
					.findViewById(R.id.map_poi_number_Of_Letters);
			ImageView closePopup = (ImageView) view
					.findViewById(R.id.map_poi_close);

			mapPoiName.setText(item.getTitle());
			mapPoiAddress.setText(item.getSnippet());
			mapPoiCity.setText(item.getCity());
			totalOfLeter.setText(item.getCountLetter());

			closePopup.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					if (panel != null) {
						panel.hide();
					}
				}

			});

			panel.show(item.getPoint());
			mapview.invalidate();
		}

	}

	// Draw all marker
	private void drawPoiItem() {
		List<Overlay> listOfOverlay = mapview.getOverlays();
		listOfOverlay.clear();
		listOfOverlay.add(new PoiItemOverlay());
		me = new MyLocationOverlay(this, mapview);
		listOfOverlay.add(me);
		mapview.invalidate();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (isHelpSoFarScreen) {
				finish();
			} else {
				setHelpSoFarView();
			}
		}
		return true;
	}

	private class DrawPoiTask extends AsyncTask<Void, Void, Void> {
		ProgressDialog dialog;

		public DrawPoiTask() {
			dialog = new ProgressDialog(Statistics.this);
			dialog.setMessage("Waiting...");
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog.show();
		}

		@Override
		protected Void doInBackground(Void... params) {
			try {
				ObjectUtils.allLocationInfo = WebService.getSingletonService()
						.getNYPLLocationCollection();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (XmlPullParserException e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			if (dialog.isShowing()) {
				dialog.dismiss();
			}
			// get all location info
			mListOfLocation = ObjectUtils.allLocationInfo;
			if (mListOfLocation != null && mListOfLocation.size() > 0) {
				LibraryLocation tmp = mListOfLocation.get(0);
				firstPoint = new GeoPoint((int) (tmp.getLat() * 1E6),
						(int) (tmp.getLon() * 1E6));

				drawPoiItem();
				if (firstPoint != null)
					mapController.animateTo(firstPoint);
			}
		}
	}

	private class InitDataTask extends AsyncTask<Void, Void, Void> {
		ProgressDialog dialog;
		String goalStr = "";
		int totalLetterInt = 0;
		int totalDonateInt = 0;
		String tmpTotalLetter = "";
		String tmpTotalDonate = "";
		private int maxLetter = 0;
		private int maxDonate = 0;

		public InitDataTask() {
			dialog = new ProgressDialog(Statistics.this);
			dialog.setMessage("Waiting...");
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			if (dialog.isShowing()) {
				dialog.dismiss();
			}

			initFormHelpSoFar();
		}

		@Override
		protected void onPreExecute() {
			dialog.show();
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) {
			try {

				goalStr = WebService.getSingletonService().getNYPLGoal();
				tmpTotalLetter = WebService.getSingletonService()
						.getTotalAdvocacyLetterCount();
				tmpTotalDonate = WebService.getSingletonService()
						.getTotalDonation();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (XmlPullParserException e) {
				e.printStackTrace();
			}
			return null;
		}

		private void initFormHelpSoFar() {
			if (goalStr != null && !goalStr.equals("")) {
				String[] arr = goalStr.split(",");
				if (arr != null && arr.length > 0) {
					goalLetter.setText("GOAL: "
							+ String.valueOf(Math.round(Double
									.parseDouble(arr[0]))));
					goalRaise.setText("GOAL: $ "
							+ String.valueOf(Math.round(Double
									.parseDouble(arr[1]))));
					maxLetter = Integer.parseInt(String.valueOf(Math
							.round(Double.parseDouble(arr[0]))));
					maxDonate = Integer.parseInt(String.valueOf(Math
							.round(Double.parseDouble(arr[1]))));

				}
			}
			if (tmpTotalLetter != null && !tmpTotalLetter.equals("")) {
				totalLetter.setText(tmpTotalLetter + " LETTERS WRITTEN");
				totalLetterInt = Math.round(Float.parseFloat(tmpTotalLetter));
			}

			if (tmpTotalDonate != null && !tmpTotalDonate.equals("")) {
				totalDonateInt = Math.round(Float.parseFloat(tmpTotalDonate));
				totalDonateInt += 16268;
				totalRaise.setText(totalDonateInt + " RAISED");
			}
			if (maxLetter != 0) {
				progressBarLetter.setMax(maxLetter);
				progressBarLetter
						.setProgress(Math
								.round(((float) totalLetterInt / maxLetter)
										* maxLetter));

			}

			if (maxDonate != 0) {
				progressBarRaise.setMax(maxDonate);
				progressBarRaise
						.setProgress(Math
								.round(((float) totalDonateInt / maxDonate)
										* maxDonate));
			}

		}
	}

}
